const db = require('../db/index')


exports.getArtCates = (req, res) => {
  const sql = 'select * from text where is_delete = 0 order by id asc'
  db.query(sql, (err, results) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      message: '获取文章分类数据成功',
      data: results
    })
  }
  )

}
exports.addArticleCates = (req, res) => {
  const sql = 'select * from text where name=? or alias = ?'
  db.query(sql, [req.body.name, req.body.alias], (err, results) => {
    if (err) return res.cc(err)
    if (results.length === 2) return res.cc('分类名称和分类别名被占用，请更换重试')
    if (results.length === 1 && results[0].name === req.body.name && results[0].alias === req.body.alias)
      return res.cc('分类名称和分类别名被占用，请更换重试')
    if (results.length === 1 && results[0].name === req.body.name)
      return res.cc('分类名称被占用，请更换重试')
    if (results.length === 1 && results[0].alias === req.body.alias)
      return res.cc('分类别名被占用，请更换重试')
    const sql = 'insert into text set ?'
    db.query(sql, req.body, (err, results) => {
      if (err)
        return res.cc(err)
      // return res.send({ status: 1, message: err.message })

      if (results.affectedRows !== 1) return res.cc('新增文章分类失败'
      )
      res.cc('新增文章分类成功', 0)

    })

  })

}
exports.deleteCateByid = (req, res) => {
  const sql = 'update text set is_delete =1 where id=?'
  db.query(sql, req.params.id, (err, results) => {
    if (err)
      return res.cc(err)
    if (results.affectedRows !== 1) return res.cc('删除文章分类失败'
    )
    res.cc('删除文章分类成功', 0)
  })
}
exports.getArtCateByid = (req, res) => {
  const sql = 'select * from text where id=? '
  db.query(sql, req.params.id, (err, results) => {
    if (err)
      return res.cc(err)
    if (results.length !== 1) return res.cc('获取文章分类数据失败'
    )
    res.send({
      status: 0,
      message: '获取文章数据成功！',
      data: results[0]
    })
  })
}
exports.updateCateById = (req, res) => {
  const sql = 'select * from text where id <>? and (name=? or alias=? )'
  db.query(sql, [req.body.id, req.body.name, req.body.alias], (err, results) => {
    if (err) return res.cc(err)
    if (results.length === 2) return res.cc('分类名称和分类别名被占用，请更换重试')
    if (results.length === 1 && results[0].name === req.body.name && results[0].alias === req.body.alias)
      return res.cc('分类名称和分类别名被占用，请更换重试')
    if (results.length === 1 && results[0].name === req.body.name)
      return res.cc('分类名称被占用，请更换重试')
    if (results.length === 1 && results[0].alias === req.body.alias)
      return res.cc('分类别名被占用，请更换重试')
    const sql = 'update text set ? where id=?'
    db.query(sql, [req.body, req.body.id], (err, results) => {
      if (err)
        return res.cc(err)
      if (results.affectedRows !== 1) return res.cc('更改文章分类失败'
      )
      res.cc('更改文章分类成功！', 0)
    })

  })

}